package org.example.sys.ui.dashboard

import androidx.databinding.ObservableBoolean
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.example.sys.App
import org.example.sys.SingleLiveEvent
import org.example.sys.bean.Book

class DetailViewModel : ViewModel() {

    val detailLiveData = SingleLiveEvent<State>()
    val unLock = ObservableBoolean()
    val book = MutableLiveData<Book>()

    val saveOrUpdate = fun(book: Book) {
        CoroutineScope(Dispatchers.IO).launch {
            App.bookApi.apply {
                try {
                    val responseData = saveOrUpdate(book).execute().body()
                    if (responseData?.code == 0) {
                        if (book.id == 0)
                            detailLiveData.postValue(State.SaveSuccess)
                        else
                            detailLiveData.postValue(State.UpdateSuccess)
                    } else {
                        detailLiveData.postValue(State.Failed)
                    }

                } catch (e: Exception) {
                    detailLiveData.postValue(e.message?.let { State.Error.setMsg(it) })
                }
            }
        }
    }


    enum class State {
        SaveSuccess, UpdateSuccess, Failed, Error;

        private var msg: String? = null
        fun setMsg(msg: String): State {
            this.msg = msg
            return this
        }
    }
}